import bcrypt from "bcryptjs";
import CryptoJS from "crypto-js";

export class BcryptUtil {
  public static async encodePassword(password: string): Promise<string> {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  }

  /**
   *
   * @param password input password
   * @param hashedPassword db hashedpassword
   * @returns
   */
  public static async verifyPassword(
    password: string,
    hashedPassword: string
  ): Promise<boolean> {
    const isMatch = await bcrypt.compare(password, hashedPassword);
    return isMatch;
  }
}
function generateRandomBytes(length: number): Uint8Array {
  if (typeof window !== "undefined" && window.crypto) {
    // 浏览器环境
    const array = new Uint8Array(length);
    window.crypto.getRandomValues(array);
    return array;
  } else if (typeof require !== "undefined") {
    // Node.js 环境
    const crypto = require("crypto");
    return new Uint8Array(crypto.randomBytes(length).buffer);
  } else {
    throw new Error("不支持的运行环境");
  }
}
export function encryptWithAES(message: string, key: any, iv: any) {
  key = CryptoJS.enc.Utf8.parse(key.toString("hex"));
  iv = CryptoJS.enc.Utf8.parse(iv.toString("hex"));
  const encrypted = CryptoJS.AES.encrypt(message, key, {
    iv,
    mode: CryptoJS.mode.CBC, // 加密模式，这里使用CBC模式
    padding: CryptoJS.pad.Pkcs7, // 填充方式
  });
  return encrypted.toString();
}

export function decryptWithAES(ciphertext: string, key: any, iv: any) {
  key = CryptoJS.enc.Utf8.parse(key.toString("hex"));
  iv = CryptoJS.enc.Utf8.parse(iv.toString("hex"));
  const decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}
export function encryptAESDefault(message: string) {
  return encryptWithAES(message, defaultKey, defaultIv);
}
export function decryptAESDefault(ciphertext: string) {
  return decryptWithAES(ciphertext, defaultKey, defaultIv);
}
const defaultKey = "57711c17bd303059f906ffb148e0503c";
const defaultIv = "9be125ed7bc04102d2a106a35b347edb";
function test() {
  const crypto = require("crypto");
  let key = crypto.randomBytes(16).toString("hex");
  // 初始化向量，长度为16字节
  let iv = crypto.randomBytes(16).toString("hex");
  // key = CryptoJS.enc.Utf8.parse(key.toString("hex"));
  // iv = CryptoJS.enc.Utf8.parse(iv.toString("hex")); // 初始化向量，长度和密钥相关，这里是AES-128的示例
  console.log(`key: ${key}`);
  console.log(`iv: ${iv}`);
  const originalMessage = "This is a secret message";
  // const encryptedMessage = encryptWithAES(originalMessage, key, iv);
  const encryptedMessage = encryptAESDefault(originalMessage);
  console.log("加密后的消息:", encryptedMessage);
  // const decryptedMessage = decryptWithAES(encryptedMessage, key, iv);
  const decryptedMessage = decryptAESDefault(encryptedMessage);
  console.log("解密后的消息:", decryptedMessage);
}
// test();
